package com.example.myservice2_provider.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.myservice2_provider.Mapper.FocusMapper;
import com.example.myservice2_provider.Mapper.UserMapper;
import com.example.myservice2_provider.entity.Focus;
import com.example.myservice2_provider.entity.Users;
import com.example.myservice2_provider.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private FocusMapper focusMapper;

    @Override
    public Users login(String username, String password) {

        LambdaQueryWrapper<Users> lqw = new LambdaQueryWrapper<Users>();

        lqw.eq(Users::getUsername,username);
        lqw.eq(Users::getPwd,password);
        return this.userMapper.selectOne(lqw);
    }


    @Override
    public Users getUserInfo(Integer uid) throws Exception {
        return this.userMapper.selectById(uid);
    }

    @Override
    public int focusUser(Integer focuerId,Integer befocusId) throws Exception {
        Users beUsers = this.userMapper.selectById(befocusId);
        Users users = this.userMapper.selectById(focuerId);
        //判断是否已经关注
        LambdaQueryWrapper<Focus> lqw = new LambdaQueryWrapper<Focus>();
        lqw.eq(Focus::getFocusId,focuerId);
        lqw.eq(Focus::getBeFocusId,befocusId);
        if(this.focusMapper.selectOne(lqw)!=null){
            return 0;
        }

        //添加
        Focus focus = new Focus();
        focus.setFocusId(focuerId);
        focus.setBeFocusId(befocusId);

        System.out.println(focus);
        int insert = this.focusMapper.insert(focus);
        //关注者+1被关注者+1
        beUsers.setWatch(beUsers.getWatch()+1);
        users.setFocus(users.getFocus()+1);
        this.userMapper.updateById(users);
        this.userMapper.updateById(beUsers);


        return insert;
    }

    @Override
    public int cancelFocusUser(Integer focusId,Integer befocusId) throws Exception {
        Users beUsers = this.userMapper.selectById(befocusId);
        Users users = this.userMapper.selectById(focusId);
        //判断是否已经关注
        LambdaQueryWrapper<Focus> lqw = new LambdaQueryWrapper<Focus>();
        lqw.eq(Focus::getFocusId,focusId);
        lqw.eq(Focus::getBeFocusId,befocusId);
        if(this.focusMapper.selectOne(lqw)==null){
            return 0;
        }

        //删除
        int delete = this.focusMapper.delete(lqw);
        //关注者+1被关注者+1
        beUsers.setWatch(beUsers.getWatch()-1);
        users.setFocus(users.getFocus()-1);
        this.userMapper.updateById(users);
        this.userMapper.updateById(beUsers);


        return delete;
    }

    @Override
    public int updateUser(Users users) throws Exception {
        return this.userMapper.updateById(users);
    }
}
